package com.km.wskj.itmonitor.pager.monitor.database;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.km.wskj.itmonitor.R;
import com.km.wskj.itmonitor.http.ZxlGenericsCallback;
import com.km.wskj.itmonitor.model.DataBase;
import com.km.wskj.itmonitor.pager.base.LActivity;
import com.km.wskj.itmonitor.pager.monitor.database.domain.DbConfig;
import com.km.wskj.itmonitor.pager.monitor.database.mysql.MySQLDetailActivity;
import com.km.wskj.itmonitor.pager.monitor.database.oracle.OracleDetailActivity;
import com.km.wskj.itmonitor.pager.monitor.database.sqlserver.SQLServerDetailActivity;
import com.zxl.zxlapplibrary.adapter.BaseAdapterHelper;
import com.zxl.zxlapplibrary.global.Constant;
import com.zxl.zxlapplibrary.util.LogUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import zrc.widget.SimpleFooter;
import zrc.widget.SimpleHeader;
import zrc.widget.ZrcListView;

/**
 * @author by Xianling.Zhou on 2017/4/10.
 */
//数据库配置页面
public class DBConfigActivity extends LActivity {
    @BindView(R.id.tool_bar_back)
    ImageView toolBarBack;
    @BindView(R.id.tool_bar_title)
    TextView toolBarTitle;
    @BindView(R.id.zrcListView)
    ZrcListView mZrcListView;

    private String id;
    private MyAdapter mAdapter;
    private List<DbConfig> dbConfigs;
    int lastUpdateNum;
    int pageIndex;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_db_config);
        ButterKnife.bind(this);
        toolBarBack.setVisibility(View.VISIBLE);
        toolBarTitle.setText("配置");

        if (getIntent().hasExtra("id"))
            id = getIntent().getStringExtra("id");

        onRefresh();
        initData();
    }

    private void initData() {
        initPullToRefresh();
    }

    private void initPullToRefresh() {
        //配置listview
        ColorDrawable line = new ColorDrawable(Color.parseColor("#f1f1f1"));
        mZrcListView.setDivider(line);
        mZrcListView.setDividerHeight(1);

        //设置下拉刷新的样式（可选，但如果没有Header则无法下拉刷新）
        SimpleHeader header = new SimpleHeader(context);
        header.setTextColor(ContextCompat.getColor(context, R.color.text_gray));
        header.setCircleColor(ContextCompat.getColor(context, R.color.colorPrimary));
        mZrcListView.setHeadable(header);

        //设置加载更多的样式（可选）
        SimpleFooter footer = new SimpleFooter(context);
        footer.setCircleColor(ContextCompat.getColor(context, R.color.colorPrimary));
        mZrcListView.setFootable(footer);

        // 设置列表项出现动画（可选）
        //zListView.setItemAnimForTopIn(R.anim.topitem_in);
        mZrcListView.setItemAnimForBottomIn(R.anim.bottomitem_in);

        // 下拉刷新事件回调（可选）
        mZrcListView.setOnRefreshStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                onRefresh();
            }
        });

        // 加载更多事件回调（可选）
        mZrcListView.setOnLoadMoreStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
//                onLoadMore();
            }
        });

        // 项目选中
        mZrcListView.setOnItemClickListener(new ZrcListView.OnItemClickListener() {
            @Override
            public void onItemClick(ZrcListView parent, View view, int position, long id) {

            }
        });

        mAdapter = new MyAdapter();
        mZrcListView.setAdapter(mAdapter);
    }

    private void onRefresh() {
        pdc.databaseConfig(HTTP_TASK_TAG, id, new ZxlGenericsCallback<List<DbConfig>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                mZrcListView.setRefreshFail("数据获取失败！");
                LogUtils.e("error", e);
            }

            @Override
            public void onResponse(List<DbConfig> dcs, int i) {

                dbConfigs = dcs;
                lastUpdateNum = dcs.size();
                pageIndex = 0;

                //control
                mAdapter.notifyDataSetChanged();
                mZrcListView.setRefreshSuccess();

                if (haveMore())
                    mZrcListView.startLoadMore();
                else
                    mZrcListView.stopLoadMore();

            }
        });
    }

    private void onLoadMore() {
        pdc.databaseConfig(HTTP_TASK_TAG, id, new ZxlGenericsCallback<List<DbConfig>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                mZrcListView.setRefreshFail("数据获取失败");
                LogUtils.e("error", e);
            }

            @Override
            public void onResponse(List<DbConfig> dcs, int i) {

                lastUpdateNum = dcs.size();
                if (dcs.size() > 0) {
                    dbConfigs.addAll(dcs);
                    pageIndex++;
                }
                //control
                mAdapter.notifyDataSetChanged();
                mZrcListView.setLoadMoreSuccess();

                if (haveMore())
                    mZrcListView.startLoadMore();
                else
                    mZrcListView.stopLoadMore();

            }
        });

    }

    private boolean haveMore() {
        return lastUpdateNum > 0;
    }

    /**
     * 适配器
     */
    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            if (dbConfigs == null) {
                return 0;
            }
            return dbConfigs.size();
        }

        @Override
        public Object getItem(int position) {
            DbConfig item = dbConfigs.get(position);
            return item;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getViewTypeCount() {
            return 1;
        }

        @Override
        public int getItemViewType(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            BaseAdapterHelper helper = BaseAdapterHelper.get(context, convertView, parent, R.layout.item_db_config);
            DbConfig item = dbConfigs.get(position);

            helper.setText(R.id.tv_key, item.key);
            helper.setText(R.id.tv_value, item.value);

            return helper.getView();
        }
    }

    @OnClick(R.id.tool_bar_back)
    public void onClick() {
        finish();
    }
}
